<template>
  <gui-page class="gui-bg-white">
    <!--		<template v-slot:gFixedTop>-->
    <!--			<view class="gui-flex gui-row gui-nowrap gui-space-between gui-padding-x">-->
    <!--				<view class=""></view>-->
    <!--				<text-->
    <!--						class="gui-bg-primary gui-color-white demo-sub-btn gui-block"-->
    <!--						@tap="submit">{{subtxt}}</text>-->
    <!--			</view>-->
    <!--		</template>-->
    <template v-slot:gBody>
      <view style="height: 100rpx"></view>

      <view class="gui-bg-white gui-dark-bg-level-3 gui-padding">
        <gui-xhs-upload-images
          id="uploadimgcom"
          :formData="{ fileSavePath: '/notes' }"
          fileName="file"
          @change="change"
          ref="uploadimgcom"
          @uploaded="uploaded"
          :uploadServerUrl="$uploadUrl"
        ></gui-xhs-upload-images>
      </view>

      <view class="gui-margin-top gui-bg-white gui-padding-x">
        <input
          style="padding: 20rpx"
          type="text"
          class="gui-form-input"
          v-model="note.noteTitle"
          name="name2"
          placeholder="添加标题"
        />

        <view
          class="gui-title-line gui-margin-top"
          style="width: 100%; height: 1rpx"
        ></view>

        <textarea
          style="width: 100%; padding: 20rpx"
          v-model="note.noteContent"
          class="gui-textarea"
          placeholder="添加正文"
        ></textarea>

        <view
          class="footer gui-flex gui-align-items-center gui-row gui-space-around"
        >
          <view
            @tap="deleteNote"
            type="default"
            class="gui-button-mini xhs-border-radius50"
            style="
              width: 30%;
              background: rgba(236, 233, 233, 0.39);
              text-align: center;
            "
          >
            <text class="gui-icons">删除笔记</text>
          </view>

          <view
            @tap="submit"
            type="default"
            class="gui-button-mini xhs-border-radius50"
            style="width: 60%; background: #ff3749; text-align: center"
          >
            <text class="gui-color-white gui-icons">编辑笔记</text>
          </view>
        </view>
      </view>
    </template>
  </gui-page>
</template>
<script>
import graceChecker from "@/Grace6/js/checker.js";
import Compressor from "compressorjs";
import commonMixin from "@/mixin/commonMinxin";

export default {
  mixins: [commonMixin],
  data() {
    return {
      // 记录需要上传的图片数据
      needPploadedImgs: [],
      note: {
        noteTitle: "",
        // 文本框输入内容记录
        noteContent: "",
      },
      // 上传按钮名称
      subtxt: "+ 发布",
      noteId: "",
    };
  },
  onLoad: function (e) {
    // uni.hideTabBar()
    this.noteId = e.noteId;
    uni.app.checkLogin();
    console.log(this.$uploadUrl);
    this.getNoteDetail();
    // 模拟 api 加载默认图片
    // 不需要默认值删除此函数即可
    // setTimeout(()=>{
    // 	this.$refs.uploadimgcom.setItems(
    // 			[
    // 				'https://images.unsplash.com/photo-1663524789630-b18292c8de6e?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyMTN8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=200&q=80',
    // 				'https://images.unsplash.com/photo-1663623483427-3d9b5d35cc61?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxOTl8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=200&q=80',
    // 				'https://images.unsplash.com/photo-1663593675908-ccb95d32b644?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyMDR8fHxlbnwwfHx8fA%3D%3D&auto=format&fit=crop&w=200&q=80'
    // 			]);
    // }, 1000);
  },
  methods: {
    deleteNote() {
      uni.app.confirm(
        "确定要删除这条笔记？",
        "确定",
        "取消",
        () => {
          uni.app.post("/auth/deleteNote", this.note, "json", "", (res) => {
            console.log(res);
            uni.switchTab({ url: "/pages/switchPages/index" });
            this.needPploadedImgs = this.$options.data().needPploadedImgs;
            this.note = this.$options.data().note;
            this.$refs.uploadimgcom.setItems([]);
          });
        },
        () => {},
      );
    },
    getNoteDetail() {
      uni.app.get("/getNote", { noteId: this.noteId }, "", (res) => {
        this.note = res.data;
        if (this.note.imgList) {
          console.log(this.note.imgList);
          this.$refs.uploadimgcom.setItems([...this.note.imgList]);
        }
      });
    },

    // 记录选择图片时的待提交数据
    change: function (e) {
      this.needPploadedImgs = e;
    },
    // 提交动态
    // 过程说明 :
    // 点击提交按钮 > 首先执行组件的上传函数 > 上传成功后获得已经上传的图片数据 > 提交给后端 api 记录整个内容
    submit: function () {
      // 阻止重复提交
      // if(this.subtxt != '+ 发布'){return ;}
      // 判断图片选择数量
      if (this.needPploadedImgs.length < 1) {
        uni.showToast({ title: "请选择图片", icon: "none" });
        return;
      }

      var rule = [
        {
          name: "noteContent",
          checkType: "string",
          checkRule: "1,9999",
          errorMsg: "笔记内容不能为空",
        },
        {
          name: "noteTitle",
          checkType: "string",
          checkRule: "1,9999",
          errorMsg: "笔记标题不能为空",
        },
        //......
      ];

      var checkRes = graceChecker.check(this.note, rule);
      if (!checkRes) {
        console.log(graceChecker.error);
        uni.app.msg(graceChecker.error);
        return;
      }

      this.subtxt = "提交中，请稍候 ...";
      this.$refs.uploadimgcom.upload();
      // 代码执行到这里，组件开始执行上传工作
      // uni-app 上传api 一次上传一个图片
      // 组件会一个一个循环上传
      // 上传完毕后会触发组件的 uploaded 事件
      // uploaded 事件意味着上传工作完毕
      // 事件会携带上传完成的图片数据 [数组格式]
    },
    getFileId(url) {
      let fileNameWithExtension = url.split("/").pop(); //获取文件名带后缀
      let dotIndex = fileNameWithExtension.lastIndexOf("."); //找到最后一个点的位置
      let fileNameWithoutExtension = fileNameWithExtension.substring(
        0,
        dotIndex,
      );
      return fileNameWithoutExtension;
    },
    // 图片上传完毕执行 uploaded 函数
    uploaded: function (uploadedImgs) {
      this.subtxt = "+ 发布";

      console.log("图片上传完毕，开始提交数据");
      console.log(uploadedImgs);
      for (let item of uploadedImgs) {
        if (!item.result) {
          const fileId = this.getFileId(item.url);
          if (fileId) {
            // 创建一个新的对象，包含动态设置的属性
            const newResult = Object.assign({}, item.result, {
              result: {
                fileId: fileId,
              },
            });
            item.result = newResult;
          }
        }
      }
      // 组合数据给后端 api 提交
      const new_imgs = uploadedImgs.map((item) => item.result.result.fileId);

      var sendData = {
        imgs: new_imgs,
        // 其他表单数据
        ...this.note,
      };
      console.log("全部数据 :");
      console.log(sendData);
      // 至此数据以及收集完毕
      // 请自己完成数据提交工作

      uni.app.post("/auth/updateNote", sendData, "json", "", (res) => {
        console.log(res);
        uni.switchTab({ url: "/pages/switchPages/index" });
        this.needPploadedImgs = this.$options.data().needPploadedImgs;
        this.note = this.$options.data().note;
        this.$refs.uploadimgcom.setItems([]);
      });
    },
  },
};
</script>
<style scoped>
.footer {
  height: 100rpx;
  padding: 15rpx;
  width: 100%;
  position: fixed;
  z-index: 999;
  left: 0;
  bottom: 80rpx;
}
</style>
